package com.nchuoj.answer.controller;

import com.feign.config.enums.RedisHead;
import com.feign.message.Question2JudgeMessage;
import com.feign.pojo.JudgeTestCase;
import com.nchuoj.answer.pojo.AnswerQuestion;
import com.nchuoj.answer.pojo.AnswerTestCase;
import com.nchuoj.answer.service.AnswerQuestionService;
import com.nchuoj.answer.service.AnswerTestCaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author lenovo
 */
@RestController
@Slf4j
public class AnswerController {
    private final AnswerQuestionService answerQuestionService;

    private final AnswerTestCaseService answerTestCaseService;

    private final RedisTemplate<String,Object> redisTemplate;

    @Autowired
    public AnswerController(AnswerQuestionService answerQuestionService, AnswerTestCaseService answerTestCaseService, RedisTemplate<String,Object> redisTemplate) {
        this.answerQuestionService = answerQuestionService;
        this.answerTestCaseService = answerTestCaseService;
        this.redisTemplate = redisTemplate;
    }


    /***
     * 创建一条答题记录
     * @param message 从判题机-题目的消息队列中的消息
     * @return 返回是否记录成功
     */
    @GetMapping("record")
    boolean recordAnswer(@RequestParam Question2JudgeMessage message) {
        message = Optional.ofNullable(message).orElse(new Question2JudgeMessage());
        List<JudgeTestCase> list = Optional.ofNullable(message.getTestCaseList()).orElse(new ArrayList<>());
        int sum = message.getTestCaseList().stream()
                .filter(JudgeTestCase::isFlag).mapToInt(JudgeTestCase::getScore).sum();
        if (sum != message.getSumScore()) {
            message.setSumScore(sum);
        }

        AnswerQuestion one = answerQuestionService.record(message.getUserId(), message.getQuestionId(),
                message.getQuestionSetId(), message.getCode(), message.getSumScore());
        redisTemplate.opsForValue().set(RedisHead.ANSWER_QUESTION.getRedisHead() + one.getUserId()
                + one.getQuestionSetId() + one.getQuestionId(), one);

        List<AnswerTestCase> answerTestCaseList = answerTestCaseService.record(one.getQuestionId(), list);
        redisTemplate.opsForValue().set(RedisHead.ANSWER_TEST_CASE.getRedisHead()+ one.getUserId()
                + one.getQuestionSetId() + one.getQuestionId(), answerTestCaseList);
        return true;
    }
}
